<?php

namespace app\index\controller;

use app\BaseController;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;

class Cart extends BaseController
{
    /**
     * 购物车首页
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $cart = Db::table("shop_cart")
                ->alias("c")
                ->leftJoin(["shop_goods" => "g"],"c.goods_id = g.id")
                ->field(["c.*","g.title","g.image","g.price","g.intro"])
                ->select();
        MyViewAssign([
            "cart" => $cart,
        ]);
        return MyView();
    }

    /**
     * 加入购物车
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        if (Request::method() == "POST"){
            $all = Request::param();
            $good = Db::table("shop_goods")->where("id",$all['good_id'])->find();
            // 判断添加购物车商品是否存在
            if (empty($good)){
                echo json_encode(['code' => 0, 'msg' => '该商品不存在']);
                return redirect("/index/index/index");
            }
            if (empty($all["id"])){
                $cartOld = Session::has("carts") ? Session::get("carts") : [];
                // 判断是否有设置Session
                if (key_exists($all["good_id"],$cartOld)){
                    // 如果有，执行加操作
                    $cartOld[$all["good_id"]] += $all["num"];
                }else{
                    // 如果没有，执行追加操作
                    $cartOld[$all["good_id"]] = $all["num"];
                }
                // 设置Session
                Session::set("carts",$cartOld);
                //成功
                echo json_encode(['code'=>0,'msg'=>'加入购物车成功']);
            }else{
                // 判断当前用户是否已经添加该商品到购物车
                $cart = Db::table("shop_cart")->where("goods_id",$all['good_id'])->find();
                if ($cart){
                    $cart["num"] += $all["num"];
                    $cart['up_time'] = time();
                    $insert = Db::table("shop_cart")->update($cart);
                }else{
                    $data['user_id'] = $all['id'];
                    $data['goods_id'] = $all["good_id"];
                    $data['num'] = $all["num"];
                    $data['status'] = 1;
                    $data['add_time'] = $data["up_time"] = time();
                    $insert = Db::table('shop_cart')->insert($data);
                }
                if($insert){  //成功
                    echo json_encode(['code'=>0,'msg'=>'加入购物车成功']);
                    exit;
                }else{  //失败
                    echo json_encode(['code'=>1,'msg'=>'加入购物车失败']);
                    exit;
                }
            }
        }
    }

    /**
     * 购物车编辑
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        if (Request::method() == "POST"){
            $all = Request::param();
            // 判断是否登录
            if(!Session::has('id')){
                // 没有登录，Session中数据
                $cartOld = Session::has("carts") ? Session::get("carts") : [];
                // 判断是否有设置Session
                if (key_exists($all["id"],$cartOld)){
                    // 如果有，执行加操作
                    $cartOld[$all["id"]] += $all["num"];
                }else{
                    // 如果没有，执行追加操作
                    $cartOld[$all["id"]] = $all["num"];
                }
                // 设置Session
                Session::set("carts",$cartOld);
            }else{
                $uid = Session::get("id");
                $cart = Db::table("shop_cart")->where("goods_id",(int)$all["id"])->where("user_id",$uid)->field(["id","num"])->find();
                $cart["num"] = $all["num"];
                Db::table("shop_cart")->where("id",$cart["id"])->update($cart);
            }
        }
    }

    /**
     * 删除购物车
     * @throws \think\db\exception\DbException
     */
    public function del()
    {
        if (Request::method() == "POST"){
            $all = Request::param();
            $user_id = Session::get("id") ? Session::get("id") : 0;
            $res = Db::table("shop_cart")
                    ->where("goods_id",$all['id'])
                    ->where("user_id",$user_id)
                    ->delete();
            if($res){  //成功
                echo json_encode(['code'=>0,'msg'=>'删除成功']);
                exit;
            }else{  //失败
                echo json_encode(['code'=>1,'msg'=>'删除失败']);
                exit;
            }
        }
    }
}